package com.kugou.test.helper;

import com.elvishew.xlog.XLog;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by sijiluo on 2016/4/6.
 */
public class HttpHelper {
    static public String request(String url) throws Exception {
        if ( !url.contains("://") ){
            url = "http://" + url; // 默认http
        }

        URL _url = new URL(url); // 新建一个URL对象
        HttpURLConnection urlConn = (HttpURLConnection) _url.openConnection(); // 打开一个HttpURLConnection连接
        urlConn.setConnectTimeout(6 * 1000); // 设置连接超时时
        urlConn.connect(); // 开始连接
        InputStream in = urlConn.getInputStream();

        ByteArrayOutputStream out= new ByteArrayOutputStream();
        int BUFFER_SIZE = 4096;
        byte[] data = new byte[BUFFER_SIZE];
        int count = -1;
        while((count = in.read(data,0,BUFFER_SIZE)) != -1) {
            out.write(data, 0, count);
        }

        data = null;
        urlConn.disconnect();// 关闭连接
        return new String(out.toByteArray(),"ISO-8859-1");
    }

    // 检查url是否可用
    static public boolean check(String url) {
        boolean is_ok = true;

        try {
            HttpHelper.request(url);
        } catch (Exception e) {
            XLog.e( String.format("check_url %s crash.",url), e);
            is_ok = false;
        }

        return  is_ok;
    }

}
